package cn.changeforyou.web.cloud.auth.interceptor;

import cn.changeforyou.utils.checker.RegExpValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author laoxu
 * @Date 2019/11/3 13:45
 **/
@Component
@Slf4j
public class RestfulInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String restful = request.getHeader("restful");
        if ("true".equals(restful)) {
            String requestURI = request.getRequestURI();
            int index = requestURI.lastIndexOf("/");
            if (index + 1 < requestURI.length()) {
                String resouceCode = requestURI.substring(index + 1);
                if (RegExpValidatorUtils.isNumber(resouceCode)) {
                    String newUrl = requestURI.substring(0, index + 1) + "?id=" + resouceCode;
                    log.info("发现restful风格的请求:{},转换为:{}", requestURI, newUrl);
                    System.out.println(newUrl);
                    request.getRequestDispatcher(newUrl).forward(request, response);
                }
            }
        }

        return true;
    }
}